<?php

namespace app\api\controller\wanlshop;

use app\api\service\ActivityService;
use app\api\service\PerformanceService;
use app\api\service\PromoteService;
use app\api\service\UserService;
use app\common\controller\Api;
use addons\wanlshop\library\EasyWeChat\Easywechat;
use addons\wanlshop\library\WanlChat\WanlChat;

use app\common\library\Sms;
use app\common\model\UserExtra;
use fast\Random;
use fast\Http;

use think\Validate;
use think\db;
use think\Log;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * WanlShop会员接口
 */
class Changegoos extends Api
{
    protected $noNeedLogin = ["timing_verification",];
    protected $noNeedRight = ["timing_verification","change_goos_list","change_goos","check_goods","get_my_change_money"];

    public function _initialize(){
        parent::_initialize();
    }

    //获取换货商品列表
    public function change_goos_list(){
        $user_id = $this->auth->id;
        if(!$user_id){
            $this->error("请登录后再试");
        }
        //查询用户信息
        $user = db("user")->where("id",$user_id)->find();
        //判断用户信息
        if (!$user){
            $this->error("用户信息有误");
        }
        $my_change_price = $this->verify_change_goos($user_id);
        $change_goods_list = db("wanlshop_change_goods")->where("money","<=",$my_change_price)->whereNull("deletetime")->field("id,goods_id,number,money,shop_id,price")->select();
        foreach($change_goods_list as &$v){
            $v["shopname"] = db("wanlshop_shop")->where("id",$v["shop_id"])->value("shopname");
            $v["goods_name"] = db("wanlshop_goods")->where("id",$v["goods_id"])->value("title");
            $v["sku_name"] = db("wanlshop_goods_sku")->where("goods_id",$v["goods_id"])->value("difference");
            unset($v["shop_id"]);
            unset($v["goods_id"]);
        }
        $change_goods_list_new = db("wanlshop_change_goods")->where("money",">",$my_change_price)->whereNull("deletetime")->field("id,goods_id,number,money,shop_id,price")->select();
        foreach($change_goods_list_new as &$v1){
            $v1["shopname"] = db("wanlshop_shop")->where("id",$v1["shop_id"])->value("shopname");
            $v1["goods_name"] = db("wanlshop_goods")->where("id",$v1["goods_id"])->value("title");
            $v1["sku_name"] = db("wanlshop_goods_sku")->where("goods_id",$v1["goods_id"])->value("difference");
            unset($v1["shop_id"]);
            unset($v1["goods_id"]);
            $change_goods_list[] = $v1;
        }
        if (count($change_goods_list) != 0) {
            $this->success("获取成功",$change_goods_list);
        }else{
            $this->error("暂无可换货商品");
        }
    }


    //获取我的换货余额
    private function verify_change_goos($user_id) {
        //定义升星商品id
        $goods_id_arr = [24, 23, 22, 21, 20, 19, 16, 9, 15, 14, 13, 4, 11];
        $time = time();
        $start = $time - 86400 * 3;
        //获取近三日下单的所有商品
        $myPrice = db("wanlshop_order")
            ->alias("order")
            ->join('wanlshop_order_goods goods','order.id = goods.order_id')
            ->where("order.user_id",$user_id)
            ->where("goods.goods_id","in",$goods_id_arr)
            ->where("order.state",8)
            ->where("order.createtime","between",[$start,$time])
            ->sum("goods.actual_payment");
        // if($myPrice == 0){
        //     $myPrice = db("user")->where("id",$user_id)->value("change_price");
        // }else{
        $myPrice = bcadd($myPrice,db("user")->where("id",$user_id)->value("change_price"),2);
        // }
        return $myPrice;
    }

    public function get_my_change_money(){
        $user_id = $this->auth->id;
        if(!$user_id){
            $this->error("请登录后再试");
        }
        //查询用户信息
        $user = db("user")->where("id",$user_id)->find();
        //判断用户信息
        if (!$user){
            $this->error("用户信息有误");
        }
        $my_change_price = $this->verify_change_goos($user_id);
        $this->success("获取成功",$my_change_price);
    }

    private function change_goos_money($user_id) {
        //定义升星商品id
        $goods_id_arr = [24, 23, 22, 21, 20, 19, 16, 9, 15, 14, 13, 4, 11];
        $time = time();
        $start = $time - 86400 * 3;
        //获取近三日下单的所有商品
        $myPrice = db("wanlshop_order")
            ->alias("order")
            ->join('wanlshop_order_goods goods','order.id = goods.order_id')
            ->where("order.user_id",$user_id)
            ->where("goods.goods_id","in",$goods_id_arr)
            ->where("order.state",8)
            ->where("order.createtime","between",[$start,$time])
            ->sum("goods.actual_payment");
        return $myPrice;
    }

    //换货接口
    public function change_goos(){
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $user_id = $this->auth->id;
            // $user_id = 11431;//$this->auth->id;
            if(!$user_id){
                $this->error("请登录后再试");
            }
            $goodsid = input("post.change_goods_id");
            if(!$goodsid){
                $this->error("请选择换货商品");
            }
            $check_change_goods = db("wanlshop_change_goods")
                ->where(['id' => $goodsid])
                ->find();
            if(!$check_change_goods){
                $this->error("换货商品信息有误");
            }
            $goods_data = db("wanlshop_goods")->where("id",$check_change_goods["goods_id"])->whereNull("deletetime")->find();
            if(!$goods_data){
                $this->error("换货商品信息缺失");
            }
            $shop_data = db("wanlshop_shop")->where("id",$check_change_goods["shop_id"])->whereNull("deletetime")->find();
            if(!$shop_data){
                $this->error("换货商品店铺信息有误!");
            }
            $address_id = input("post.address");
            if(!$address_id){
                $this->error("请选择收货地址");
            }
            $address = db("wanlshop_address")
                ->where(['id' => $address_id,'user_id' =>$user_id])
                ->find();
            if(!$address){
                $this->error("收货地址有误");
            }
            $sku = db("wanlshop_goods_sku")
                ->where(['id' => $check_change_goods["sku_id"]])
                ->find();
            if(!$sku){
                $this->error("商品sku信息有误");
            }
            //查询用户信息
            $user = db("user")->where("id",$user_id)->find();
            //判断用户信息
            if (!$user){
                $this->error("用户信息有误");
            }
            $check_change_money = 1;
            $my_change_price = $this->verify_change_goos($user_id);
            if($check_change_goods["money"] > $my_change_price){
                $check_change_money = 0;
                $my_money = $user["money"];
                $money_pay = $check_change_goods["money"] - $my_change_price;
                if($money_pay > $my_money){
                    $this->error("亲！您的换货金额加上积分不够兑换此商品，请重新选择！");
                }

            }
            $check_is_change = $this->get_change_goos($user_id);
            $change_goos_money = $this->change_goos_money($user_id);
            if($check_is_change){
                $order_id_list = $check_is_change;
                db("wanlshop_order")->where("id","in",$order_id_list)->update(["state"=>9,"updatetime"=>time()]);
                db("user")->where("id",$user_id)->inc("change_price",$change_goos_money)->update(["updatetime"=>time()]);
                $yue = $this->auth->change_price - $check_change_goods['money'];
                // 数据库事务操作
                Db::startTrans();
                try {
                    $new_wanlshop_order = [
                        "user_id" => $user_id,
                        "shop_id" => $check_change_goods["shop_id"],
                        "order_no" => $check_change_goods["shop_id"].$user_id,
                        "address_id" => $address_id,
                        "state" => 2,
                        "remarks" => "用户:".$user["username"]." vip产品换货;换货订单号=>".json_encode($order_id_list)." 换货前余额:".$this->auth->change_price . " 换货后余额:" . $yue,
                        "createtime" => time(),
                        "paymenttime" => time(),
                    ];
                    $get_new_order_id = db("wanlshop_order")->insertGetId($new_wanlshop_order);
                    $wanlshop_order_goods = [
                        'order_id' => $get_new_order_id, // 获取自增ID
                        'goods_id' => $check_change_goods['goods_id'],
                        'shop_id' => $check_change_goods['shop_id'],
                        'shop_name' => db("wanlshop_shop")->where("id",$check_change_goods["shop_id"])->value("shopname"),
                        'title' => $goods_data['title'],
                        'image' => $goods_data['image'],
                        'goods_sku_sn' => $sku['sn'],
                        'goods_sku_id' => $sku['id'],
                        'difference' => $sku['difference'],
                        'market_price' => $check_change_goods['money'], // 市场价
                        'price' => $check_change_goods['money'], // 原价
                        'freight_price' => 0, //快递价格
                        'discount_price' => 0, // 优惠金额
                        'actual_payment' => $check_change_goods['money'], // 1.0.6修复 实际支付，因为要和总价进行计算
                        'number' => $check_change_goods['number']
                    ];
                    $wanlshop_order_address = [
                        "user_id" => $user_id,
                        "shop_id" => $check_change_goods["shop_id"],
                        "order_id" => $get_new_order_id,
                        "name"=>$address["name"],
                        "mobile"=>$address["mobile"],
                        'address' => $address['province'].'/'.$address['city'].'/'.$address['district'].'/'.$address['address'],
                        'address_name' => $address['address_name'],
                        'location' => $address['location'],
                        "createtime"=>time(),
                        "updatetime"=>time()
                    ];
                    $balance_no = date('YmdHis') . rand(10000000,99999999);
                    $wanlshop_pay = [
                        "shop_id" => $check_change_goods["shop_id"],
                        "pay_no" => $balance_no,
                        "trade_no" => $balance_no,
                        "user_id" => $user_id,
                        "order_id" => $get_new_order_id,
                        "order_no" => $check_change_goods["shop_id"].$user_id,
                        "pay_type" => 1,
                        "pay_state" => 1,
                        "type" => "goods",
                        "number" => 1,
                        "order_price" => 0,
                        "freight_price" => 0,
                        "coupon_price" => 0,
                        "discount_price" => 0,
                        "refund_price" => 0,
                        "actual_payment" => 0,
                        "total_amount" => 0,
                        "createtime" => time(),
                        "updatetime" => time(),
                        "price" => 0,
                        'notice'  => json_encode([
                            'type' => "balance",
                            'user_id' => $user_id,
                            'trade_no' => $balance_no,
                            'out_trade_no' => $balance_no,
                            'amount' => 0,
                            'total_amount' => 0,
                            'order_id' => $get_new_order_id,
                            'trade_type' => 'BALANCE',
                            'version' => '1.0.0'
                        ])
                    ];
                    db("wanlshop_order_address")->insert($wanlshop_order_address);
                    db("wanlshop_order_goods")->insert($wanlshop_order_goods);
                    db("wanlshop_pay")->insert($wanlshop_pay);
                    if($check_change_money == 0){
                        $result = db("user")->where("id",$user_id)->dec("money",$money_pay)->dec("score",$money_pay)->update(["updatetime"=>time(),"change_price"=>0]);
                        $insert = [
                            "user_id"       => $user_id,
                            "money"         => $money_pay,
                            "before"        => $user["money"],
                            "after"         => bcadd($user["money"],$money_pay),
                            "memo"          => "用户换货余额不足,积分支付",
                            "type"          => "pay",
                            "createtime"    => time(),
                        ];
                        db("user_money_log")->insert($insert);
                    }else{
                        $result = db("user")->where("id",$user_id)->dec("change_price",$check_change_goods['money'])->update(["updatetime"=>time()]);
                    }
                    // $result = db("user")->where("id",$user_id)->dec("change_price",$check_change_goods['money'])->update(["updatetime"=>time()]);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('换货成功');
                } else {
                    $this->error(__('订单异常，换货失败'));
                }
            }elseif($this->auth->change_price > 0 && $check_is_change == false){
                $yue = $this->auth->change_price - $check_change_goods['money'];
                Db::startTrans();
                try {
                    $new_wanlshop_order = [
                        "user_id" => $user_id,
                        "shop_id" => $check_change_goods["shop_id"],
                        "order_no" => $check_change_goods["shop_id"].$user_id,
                        "address_id" => $address_id,
                        "state" => 2,
                        "remarks" => "用户:".$user["username"]." vip产品换货; 换货奖池兑换! 换货前余额:".$this->auth->change_price . " 换货后余额:" . $yue,
                        "createtime" => time(),
                        "paymenttime" => time(),
                    ];
                    $get_new_order_id = db("wanlshop_order")->insertGetId($new_wanlshop_order);
                    $wanlshop_order_goods = [
                        'order_id' => $get_new_order_id, // 获取自增ID
                        'goods_id' => $check_change_goods['goods_id'],
                        'shop_id' => $check_change_goods['shop_id'],
                        'shop_name' => db("wanlshop_shop")->where("id",$check_change_goods["shop_id"])->value("shopname"),
                        'title' => $goods_data['title'],
                        'image' => $goods_data['image'],
                        'goods_sku_sn' => $sku['sn'],
                        'goods_sku_id' => $sku['id'],
                        'difference' => $sku['difference'],
                        'market_price' => $check_change_goods['money'], // 市场价
                        'price' => $check_change_goods['money'], // 原价
                        'freight_price' => 0, //快递价格
                        'discount_price' => 0, // 优惠金额
                        'actual_payment' => $check_change_goods['money'], // 1.0.6修复 实际支付，因为要和总价进行计算
                        'number' => $check_change_goods['number']
                    ];
                    $wanlshop_order_address = [
                        "user_id" => $user_id,
                        "shop_id" => $check_change_goods["shop_id"],
                        "order_id" => $get_new_order_id,
                        "name"=>$address["name"],
                        "mobile"=>$address["mobile"],
                        'address' => $address['province'].'/'.$address['city'].'/'.$address['district'].'/'.$address['address'],
                        'address_name' => $address['address_name'],
                        'location' => $address['location'],
                        "createtime"=>time(),
                        "updatetime"=>time()
                    ];
                    $balance_no = date('YmdHis') . rand(10000000,99999999);
                    $wanlshop_pay = [
                        "shop_id" => $check_change_goods["shop_id"],
                        "pay_no" => $balance_no,
                        "trade_no" => $balance_no,
                        "user_id" => $user_id,
                        "order_id" => $get_new_order_id,
                        "order_no" => $check_change_goods["shop_id"].$user_id,
                        "pay_type" => 1,
                        "pay_state" => 1,
                        "type" => "goods",
                        "number" => 1,
                        "order_price" => 0,
                        "freight_price" => 0,
                        "coupon_price" => 0,
                        "discount_price" => 0,
                        "refund_price" => 0,
                        "actual_payment" => 0,
                        "total_amount" => 0,
                        "createtime" => time(),
                        "updatetime" => time(),
                        "price" => 0,
                        'notice'  => json_encode([
                            'type' => "balance",
                            'user_id' => $user_id,
                            'trade_no' => $balance_no,
                            'out_trade_no' => $balance_no,
                            'amount' => 0,
                            'total_amount' => 0,
                            'order_id' => $get_new_order_id,
                            'trade_type' => 'BALANCE',
                            'version' => '1.0.0'
                        ])
                    ];
                    db("wanlshop_order_address")->insert($wanlshop_order_address);
                    db("wanlshop_order_goods")->insert($wanlshop_order_goods);
                    db("wanlshop_pay")->insert($wanlshop_pay);
                    if($check_change_money == 0){
                        $result = db("user")->where("id",$user_id)->dec("money",$money_pay)->dec("score",$money_pay)->update(["updatetime"=>time(),"change_price"=>0]);
                        $insert = [
                            "user_id"       => $user_id,
                            "money"         => $money_pay,
                            "before"        => $user["money"],
                            "after"         => bcadd($user["money"],$money_pay),
                            "memo"          => "用户换货余额不足,积分支付",
                            "type"          => "pay",
                            "createtime"    => time(),
                        ];
                        db("user_money_log")->insert($insert);
                    }else{
                        $result = db("user")->where("id",$user_id)->dec("change_price",$check_change_goods['money'])->update(["updatetime"=>time()]);
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('换货成功');
                } else {
                    $this->error(__('订单异常，换货失败'));
                }
            }else{
                $this->error("您暂无换货权限");
            }
        } else {
            $this->error(__('非法请求'));
        }
    }


    //验证是否符合换货条件
    private function get_change_goos($user_id) {
        //定义升星商品id
        $goods_id_arr = [24, 23, 22, 21, 20, 19, 16, 9, 15, 14, 13, 4, 11];
        $time = time();
        $start = $time - 86400 * 3;
        //获取近三日下单的所有商品
        $order_list = db("wanlshop_order")
            ->alias("order")
            ->join('wanlshop_order_goods goods','order.id = goods.order_id')
            ->where("order.user_id",$user_id)
            ->where("goods.goods_id","in",$goods_id_arr)
            ->where("order.state",8)
            ->where("order.createtime","between",[$start,$time])
            ->field("goods.goods_id as goods_id,order.id as order_id")
            ->select();
        $order_id = array_column($order_list,"order_id");
        //比对是否从一星买到十三星
        if(count($order_id) > 0){
            return $order_id;
        }else{
            return false;
        }
    }

    public function check_goods(){
        $user_id = $this->auth->id;
        if(!$user_id){
            $this->error("请登录后再试");
        }
        //查询用户信息
        $user = db("user")->where("id",$user_id)->find();
        //判断用户信息
        if (!$user){
            $this->error("用户信息有误");
        }
        //获取近三日下单的所有商品
        $order_list = db("wanlshop_order")
            ->alias("order")
            ->join('wanlshop_order_goods goods','order.id = goods.order_id')
            ->where("order.user_id",$user_id)
            ->where("goods.goods_id",11)
            ->where("order.state",8)
            ->group("goods.goods_id")
            ->find();
        if($order_list){
            $this->success("换货商品");
        }else{
            $this->success("非换货商品");
        }

    }


    //定时脚本 更新换货商品信息
    public function timing_verification(){

        $time = date("Ymd");
        $timestamp = strtotime($time);
        $start = $timestamp - 86400 * 3;

        $order_list = db("wanlshop_order")
            ->alias("order")
            ->join('wanlshop_order_goods goods','order.id = goods.order_id')
            ->where("goods.goods_id",11)
            ->where("order.state",8)
            ->group("order.user_id")
            ->where("order.createtime","<",$start)
            ->column("order.user_id");
        $res = db("wanlshop_order")
            ->alias("order")
            ->join('wanlshop_order_goods goods','order.id = goods.order_id')
            ->where("order.user_id","in",$order_list)
            ->where("order.state",8)
            ->update(["order.state"=>2,"order.updatetime"=>time()]);
        if($res > 0){
            $this->success("更新完成",$order_list);
        }else{
            $this->error("无需更新",$order_list);
        }
    }


}